package com.kira.solo.schedule.edit

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.kira.solo.schedule.domain.FullCasesUseCase
import com.kira.solo.schedule.domain.ScheduleTasksService
import com.kira.solo.schedule.list.CaseListUiState
import com.kira.solo.schedule.pojo.CaseEditUiState
import com.kira.solo.schedule.pojo.CasePeriodTaskInfo
import com.kira.solo.schedule.pojo.PeriodType
import com.kira.solo.schedule.pojo.Time
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 *
 * @packageName com.kira.solo.schedule.edit
 * @date 2024/1/25 13:58
 * @author zhanglei
 */
@HiltViewModel
class ScheduleEditViewModel @Inject constructor(
    savedStateHandle: SavedStateHandle,
    private val fullCasesUseCase: FullCasesUseCase,
    private val service: ScheduleTasksService,
) : ViewModel() {
    private val taskId: Long = savedStateHandle["taskId"] ?: -1
    private val taskCache = MutableStateFlow(CasePeriodTaskInfo.INIT)

    init {
        viewModelScope.launch {
            service.getTask(taskId)?.let { info ->
                taskCache.update { info }
            }
        }
    }

    /**
     * 全部用例，用于选择
     */
    val allCases = fullCasesUseCase()

    /**
     * 当前task 数据
     */
    val editUiState = taskCache.map { it.toUiState }.stateIn(
        viewModelScope,
        SharingStarted.WhileSubscribed(5000),
        taskCache.value.toUiState
    )

    private val CasePeriodTaskInfo.toUiState: CaseEditUiState
        get() = CaseEditUiState(
            this,
            CaseListUiState(caseIds.mapNotNull { id -> fullCasesUseCase[id] })
        )

    /**
     * 执行时间
     */
    fun onTimeChanged(hour: Int, minute: Int) {
        taskCache.update { it.copy(time = Time(hour, minute)) }
    }

    /**
     * 执行周期
     */
    fun onPeriodChanged(periodType: PeriodType) {
        taskCache.update { it.copy(periodType = periodType) }
    }

    /**
     * 选中的用例
     */
    fun onSelectCases(ids: List<Long>) {
        taskCache.update { it.copy(caseIds = ids) }
    }

    /**
     * 完成，将任务添加到定时器中
     */
    fun onDone(): Boolean {
        if (taskCache.value.caseIds.isEmpty()) return false
        if (taskCache.value.taskId > 0L) {
            viewModelScope.launch {
                service.modifyTask(taskCache.value)
            }
        } else {
            viewModelScope.launch {
                service.addTask(taskCache.value)
            }
        }
        return true
    }
}